package com.zdy.showgoods;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.example.networklibrary.BaseObserver;
import com.example.networklibrary.MD5;
import com.example.networklibrary.RxHttp;
import com.example.networklibrary.SharedPreferencesUtils;
import com.example.networklibrary.config.KeyInterface;
import com.example.networklibrary.entity.RequestEntity;
import com.example.networklibrary.model.GuestModel;
import com.example.networklibrary.model.ProductListModel;
import com.example.networklibrary.model.RecommendModel;
import com.example.networklibrary.model.UserInfo;
import com.zdy.utils.AppUtil;
import com.zdy.utils.GlideApp;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ProductFragment extends Fragment {
    private ItemClickListener itemClickListener;
    private ProductListModel productListModel;
    private ImageView item_product_img;

    private LinearLayout properties_parent;
    public interface ItemClickListener {
        void toInfo(ProductListModel code);
    }

    public ProductFragment() {

    }


    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.item_product_top_fragment, container, false);
        item_product_img = v.findViewById(R.id.item_product_img);
        properties_parent = v.findViewById(R.id.product_property);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null) {
                    itemClickListener.toInfo(productListModel);
                }
            }
        });
        return v;

    }


    @Override
    public void onStart() {
        super.onStart();
        String code = getArguments().getString("Code");
        loadProduct(code);
        Log.e("Start", "Start");
    }

    private void loadProduct(String code) {
        RequestEntity requestEntity = new RequestEntity();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rfid", code);
        requestEntity.setBody(jsonObject);
        JSONObject header = new JSONObject();
        header.put("request_seq", KeyInterface.REQUEST_SEQ);
        header.put("sign", "");
        header.put("sys_id", KeyInterface.SYS_ID);
        header.put("tra_code", KeyInterface.SEARCHPRODUCT);
        requestEntity.setHeader(header);
        try {
            String signString = JSONObject.toJSONString(requestEntity);
            String sign = MD5.getSign(signString);
            header.put("sign", sign);
            requestEntity.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String json = "";
        try {
            json = URLEncoder.encode(JSONObject.toJSONString(requestEntity), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RxHttp.getInstance()
                .getSyncServer()
                .loadProduct(SharedPreferencesUtils.getString(getContext(), KeyInterface.AppURL), json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ProductListModel>() {
                    @Override
                    public void onSuccess(ProductListModel result) {
                        try {
                            productListModel = result;
                            insertServiceRecorde(productListModel.getSku_id() + "");
                            initView();

                            //
                            RecommendModel recommendModel = new RecommendModel();
                            recommendModel.setSku_id(productListModel.getSku_id());
                            EventBus.getDefault().post(recommendModel);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {

                    }
                });
    }

    private void initView() {
        if (productListModel == null) return;
        if (TextUtils.isEmpty(productListModel.getImage_id())) {
            GlideApp.with(getActivity()).load(R.mipmap.img_test_2).into(item_product_img);
        } else {
            String imgUrl = AppUtil.returnImgURL(getContext()) + productListModel.getImage_id();
            GlideApp.with(getActivity()).load(imgUrl).error(R.mipmap.img_test_2).into(item_product_img);
        }
        properties_parent.removeAllViews();
        for (String property : productListModel.getProperty_value_list()) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_property, null);
            TextView textView = view.findViewById(R.id.item_property_tv);
            textView.setText(property);
            properties_parent.addView(view);
        }
    }


    //插入服务记录
    private void insertServiceRecorde(String sku_id) {
        RequestEntity requestEntity = new RequestEntity();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sku_id", sku_id);


        jsonObject.put("staff_id", returnStaffId());
        jsonObject.put("customer_id", returnCustomId());

        requestEntity.setBody(jsonObject);
        JSONObject header = new JSONObject();
        header.put("request_seq", KeyInterface.REQUEST_SEQ);
        header.put("sign", "");
        header.put("sys_id", KeyInterface.SYS_ID);
        header.put("tra_code", KeyInterface.SERVICE);
        requestEntity.setHeader(header);
        try {
            String signString = JSONObject.toJSONString(requestEntity);
            String sign = MD5.getSign(signString);
            header.put("sign", sign);
            requestEntity.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String json = "";
        try {
            json = URLEncoder.encode(JSONObject.toJSONString(requestEntity), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RxHttp.getInstance()
                .getSyncServer()
                .parseJsonObject(SharedPreferencesUtils.getString(getContext(), KeyInterface.AppURL), json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<JSONObject>() {
                               @Override
                               public void onSuccess(JSONObject result) {
                               }

                               @Override
                               public void onFailure(Throwable e, String errorMsg) {


                               }
                           }
                );
    }

    private String returnStaffId() {
        String staff = SharedPreferencesUtils.getString(getContext(), KeyInterface.StaffInfo);
        UserInfo userInfo = JSONObject.parseObject(staff, UserInfo.class);
        return userInfo.getStaff_id();
    }


    private String returnCustomId() {
        String custom = SharedPreferencesUtils.getString(getContext(), KeyInterface.GuestInfo);
        GuestModel guestModel = JSONObject.parseObject(custom, GuestModel.class);
        return guestModel.getCustomer_id();
    }

}